package primary.array;

/**
 * @Author Elephas
 * @Date 2022/1/7
 **/
public class MoveZeros {
    public static void main(String[] args) {
        final int[] test01 = new int[]{0,1,0,3,12};
        final int[] test02 = new int[]{1,3,12,3,12};
        moveZeroes(test01);

    }

    /*
        解法一：记录0的个数，从前向后将非0元素向前移动
     */
    public static void moveZeroes(int[] nums){
        int zeroCount=0;
        for (int i = 0; i < nums.length; i++) {
            if(nums[i] == 0){
                zeroCount++;
            }
        }
        int left = 0,cur=0;
        while(cur < nums.length ){
            if(nums[cur]!=0){
                nums[left] = nums[cur];
                left++;
            }
            cur++;
        }
        cur = nums.length-zeroCount;
        while(cur < nums.length)
            nums[cur++]=0;
        return;
    }
    /*
        解法二：一次遍历，采用快排思想
     */
    public static void moveZeroes2(int[] nums){
        int left = -1,cur=0;
        while(cur < nums.length){
            if(nums[cur]!=0){
                swap(nums,cur,++left);
            }
            cur++;
        }
    }
    public static void swap(int[] A,int i,int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
}
